package com.daffodil.workable.factory.strategy;

import java.util.Map;

import com.daffodil.util.JacksonUtils;
import com.daffodil.util.StringUtils;
import com.daffodil.workable.entity.WorkableForm;
import com.daffodil.workable.entity.WorkableNode;
import com.daffodil.workable.entity.WorkableResult;
import com.daffodil.workable.factory.strategy.model.WorkableEmail;
import com.daffodil.workable.util.SendEmailUtils;
import com.daffodil.workable.util.WorkableUtils;

/**
 * -任务工作流-邮箱告警节点
 * @author yweijian
 * @date 2022年4月8日
 * @version 1.0
 * @description
 */
public class EmailWorkableStrategy extends DefaultWorkableStrategy {
    
    @Override
    protected WorkableResult chain(WorkableNode workableNode, WorkableResult curtResult, WorkableResult lastResult) {
        
        WorkableForm workableForm = workableNode.getWorkableForm();
        if(StringUtils.isNull(workableForm)) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数为空", workableNode.getName());
        }

        WorkableEmail workableEmail = JacksonUtils.toJavaObject(workableForm.getNodeForm(), WorkableEmail.class);
        if(StringUtils.isNull(workableEmail)) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数为空或不规范", workableNode.getName());
        }
        
        if(StringUtils.isEmpty(workableEmail.getEmail())) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数【{}】为空", workableNode.getName(), "email");
        }
        
        if(StringUtils.isEmpty(workableEmail.getSubject())) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数【{}】为空", workableNode.getName(), "subject");
        }
        
        if(StringUtils.isEmpty(workableEmail.getContent())) {
            return curtResult.error("任务工作流执行失败，【{}】节点表单参数【{}】为空", workableNode.getName(), "content");
        }
        
        Map<String, Object> variables = lastResult.getVariables();
        String[] emails = workableEmail.getEmail().split(WorkableEmail.SPLIT_TAG);
        String subject = WorkableUtils.getExpressionValue(workableEmail.getSubject(), variables);
        String content = WorkableUtils.getExpressionValue(workableEmail.getContent(), variables);
        String message = SendEmailUtils.sendEmail(subject, content, emails);
        
        curtResult.setStatus("OK".equals(message));
        curtResult.setMessage(message);
        curtResult.setVariables(variables);
        
        return curtResult;
    }
    
    

}
